package jplat.core.trans;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import jplat.base.constant.KJPlatBase;
import jplat.base.user.IUserInfoGetters;
import jplat.base.user.impl.JUserInfoGettersSession;
import jplat.error.exception.JBaseException;
import jplat.error.exception.JSystemException;
import jplat.error.exception.JTransException;
import jplat.tools.coder.JsonCoder;
import jplat.tools.config.JAppConfig;
import jplat.tools.string.JLogUtils;
import jplat.tools.string.StringUtil;

import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

public abstract class JAppBaseService
{
	private Logger logger = Logger.getLogger(JAppBaseService.class);

	protected JAppContextFactory serviceFactory = new JAppContextFactory();
	
	@ExceptionHandler(JTransException.class)
	@ResponseBody
	public String execJTransExceptionHandler( JTransException transException, HttpServletResponse response )
	{
		logger.error(JLogUtils.getExceptionLog(transException, JAppConfig.LOG_TRACE_CNT, true));
		return buildErrMessage(transException,response );
	}
	
	@ExceptionHandler(JSystemException.class)
	@ResponseBody
	public String execJTransExceptionHandler( JSystemException sysException, HttpServletResponse response )
	{
		logger.error(JLogUtils.getExceptionLog(sysException, JAppConfig.LOG_TRACE_CNT, true));
		return buildErrMessage(sysException,response);  
	}
	
	private String buildErrMessage( JBaseException sysException,HttpServletResponse response )
	{
		logger.error(sysException.getErrCode()+":"+sysException.getErrMsg());
		
		Map<String,Object> errMap = new HashMap<String,Object>();
		
		errMap.put(KJPlatBase.H_RSP_HEAD, new JClientRspHeader(sysException.getErrCode(),sysException.getErrMsg()));
		errMap.put(KJPlatBase.H_RSP_BODY, "" );

		//设置错误头.
		String errCode = StringUtil.getDefString(sysException.getErrCode(),JAppConnectInfo.V_HRETCODE_FAIL);
		response.setHeader( JAppConnectInfo.H_RET_HEAD, errCode );
//		response.setContentType("application/json;charset:utf-8");
		return JsonCoder.toJsonString(errMap);
	}

}
